package com.kh.statistics.video.core.algorithm;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Map;
import java.util.TreeMap;

public class KuaishouSig3Generator {

    private static final String HMAC_SHA256 = "HmacSHA256";

    /**
     * 使用HMAC-SHA256算法生成签名
     *
     * @param parameters 参数Map
     * @param apiKey API密钥或密文
     * @return 十六进制字符串形式的签名
     */
    public static String generateSignature(Map<String, Object> parameters, String apiKey)
            throws NoSuchAlgorithmException, InvalidKeyException {
        // 将参数按键名字母顺序进行排序
        TreeMap<String, Object> sortedParams = new TreeMap<>(parameters);

        // 拼接参数和值
        StringBuilder data = new StringBuilder();
        for (Map.Entry<String, Object> entry : sortedParams.entrySet()) {
            data.append(entry.getKey()).append(entry.getValue());
        }

        // 使用HMAC-SHA256进行哈希计算
        Mac sha256HMAC = Mac.getInstance(HMAC_SHA256);
        SecretKeySpec secretKey = new SecretKeySpec(apiKey.getBytes(StandardCharsets.UTF_8), HMAC_SHA256);
        sha256HMAC.init(secretKey);

        byte[] hash = sha256HMAC.doFinal(data.toString().getBytes(StandardCharsets.UTF_8));
        return bytesToHex(hash);
    }

    // 辅助方法，将字节转换为十六进制字符串
    private static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder(2 * bytes.length);
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }

    public static void main(String[] args) {
        try {
            Map<String, Object> parameters = new TreeMap<>();
            parameters.put("count", 10);
            parameters.put("page", 3);
            parameters.put("kuaishou.web.cp.api_ph", "7f300e2b5b859e0cb14057bf2f109bf951b9");
            String apiKey = "ChZrdWFpc2hvdS53ZWIuY3AuYXBpLnN0ErABJzsGeqJqJXeiivnPJpWOiC4vGHbe7inVebLnrAxmmTtmHf_ST-y3wwQ-U144h1pZbwqpicXL8M7HpXzGO3lk74HKcykYR3FyPq_aj0p6TE64YrfRTjMwiirJUMgBNnzijKWkIof6I6oHOYAe30STJWBWcrpwxBNsTY_0cit5flW9k-K3UB1yGC85dw9xXd2vhgFZ3qhf0wBk_wZDl7pv_h2iu-mBmEL-3eWt9PLuqIcaEh7Kteo6024TI8Igpb9lFJnv3CIgqNU8JTXbOSK4qlGoWs0M2pmsgbefvNqjg8dJmmp03IQoBTAB";

            String signature = generateSignature(parameters, apiKey);
            System.out.println("Generated NS_sig3: " + signature);
        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            e.printStackTrace();
        }
    }
}
